package application.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import application.models.Modwineusers;

import library.Controller;

/**
 * Servlet implementation class user
 */
public class user extends Controller {
	private static final long serialVersionUID = 1L;
	    
	@SuppressWarnings("unchecked")
	public void list(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException{
		String name = this.getClass().getSimpleName();
		if(request.getSession().getAttribute("user")!= null) {
			//Prepare Session
			SessionFactory sessionFactory = new Configuration()
				.configure()
				.buildSessionFactory();
			//Start session
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			

			List<Modwineusers> users = (List<Modwineusers>) session.createQuery("from Modwineusers").list();
			request.setAttribute("users", users);
			
			out.flush();
			include(request,response,"/layout/"+name+"/list.jsp");
			
			session.getTransaction().commit();
			session.close();
		}else {
			response.sendRedirect("administrator?op=login");
		}	
	}
	
	public void add(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException{
		String name = this.getClass().getSimpleName();
		if(request.getSession().getAttribute("user")!= null) {
			out.flush();
			request.setAttribute("user", null);
			include(request,response,"/layout/"+name+"/edit.jsp");
		}else {
			response.sendRedirect("administrator?op=login");
		}
	}
	
	@SuppressWarnings("unchecked")
	public void edit(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException{
		String name = this.getClass().getSimpleName();
		
		if(request.getParameter("id") == null)
			response.sendRedirect(name+"?op=list");
		String type_id = (String) request.getParameter("id");
		
		if(request.getSession().getAttribute("user")!= null) {
			//Prepare Session
			SessionFactory sessionFactory = new Configuration()
				.configure()
				.buildSessionFactory();
			//Start session
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			
			Query sql = session.createQuery("from Modwineusers where user_id =:id");
			List<Modwineusers> users = (List<Modwineusers>) sql.setString("id", type_id).list();
			if(users.isEmpty())
				response.sendRedirect(name+"?op=list");
			else {
				out.flush();
				request.setAttribute("user", (Modwineusers) users.get(0));
				include(request,response,"/layout/"+name+"/edit.jsp");
			}
			
			session.getTransaction().commit();
			session.close();			
		}else {
			response.sendRedirect("administrator?op=login");
		}
	}
	
	@SuppressWarnings({ "unchecked" })
	public void save(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException{
		//Prepare Session
		SessionFactory sessionFactory = new Configuration()
			.configure()
			.buildSessionFactory();
		//Start session
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		try {
			String name = this.getClass().getSimpleName();
			if(request.getSession().getAttribute("user")!= null) {
				String sid = null;
				if(request.getParameter("id")!= null){
					String type_id = (String) request.getParameter("id");
					Query sql = session.createQuery("from Modwineusers where user_id =:id");
					
					List<Modwineusers> users = (List<Modwineusers>) sql.setString("id", type_id).list();
					
					if(users.isEmpty()) {
						response.sendRedirect(name+"?op=list");
					} else {
						sid = users.get(0).getSession();
						session.delete(users.get(0));
					}
				}				
				
				Modwineusers user = new Modwineusers();
				
				user.setUserId(request.getParameter("user_id"));
				
				user.setName(request.getParameter("name"));
				user.setSurname(request.getParameter("surname"));
				user.setBirthplace(request.getParameter("birthplace"));
				
				DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
				Date birth = formatter.parse(request.getParameter("birthdate"));
				user.setBirthdate(birth);
				
				user.setCodFisc(request.getParameter("codFisc"));
				
				if(request.getParameter("sex").equals("1"))
					user.setSex(true);
				else
					user.setSex(false);
				
				if(request.getParameter("admin")!= null)
					user.setAdmin(true);
				else
					user.setAdmin(false);

				if(request.getParameter("active")!= null)
					user.setActive(true);
				else
					user.setActive(false);

				
				user.setMail(request.getParameter("mail"));
				user.setPassword(request.getParameter("password"));
				user.setAddress(request.getParameter("address"));
				user.setCity(request.getParameter("city"));
				user.setCap(Short.parseShort(request.getParameter("cap")));
				user.setCountry(request.getParameter("country"));
				
				if(sid == null)
					user.setSession(request.getSession().getId());
				else
					user.setSession(sid);
				
				session.save(user);
				response.sendRedirect(name+"?op=list");
				
				session.getTransaction().commit();
				session.close();			
			}else {
				response.sendRedirect("administrator?op=login");
			}
		}catch(Exception e){
			session.getTransaction().rollback();
			session.close();
			PrintWriter x = response.getWriter();
			x.write(e.toString());
		}
	}
	
	@SuppressWarnings("unchecked")
	public void delete(HttpServletRequest request, HttpServletResponse response, JspWriter out) throws ServletException, IOException {
		String name = this.getClass().getSimpleName();
		String type_id = (String) request.getParameter("id");
		if(request.getSession().getAttribute("user")!= null) {
			//Prepare Session
			SessionFactory sessionFactory = new Configuration()
				.configure()
				.buildSessionFactory();
			//Start session
			Session session = sessionFactory.openSession();
			session.beginTransaction();
			
			Query sql = session.createQuery("from Modwineusers where user_id =:id");
			List<Modwineusers> users = (List<Modwineusers>) sql.setString("id", type_id).list();
			session.delete(users.get(0));
			
			session.getTransaction().commit();
			session.close();
			
			response.sendRedirect(name+"?op=list");
		} else {
			response.sendRedirect("administrator?op=login");
		}
	}
}
